<!--
 Copyright 2024 Administrator
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<script setup lang="ts">
import { useAudioStore } from "@/store/modules/audio";
import {
  CirclePlus,
  Folder,
  Remove,
  Switch,
  View,
} from "@element-plus/icons-vue";
import { storeToRefs } from "pinia";
import {
  onBeforeMount,
  onMounted,
  reactive,
  ref,
  toRefs,
  watchEffect,
} from "vue";
import { useRoute, useRouter } from "vue-router";
/**
 * 仓库
 */
const store = useAudioStore();
const { currentTime, currentTimeStr, lrcData } = storeToRefs(store);
/**
 * 路由对象
 */
const route = useRoute();
/**
 * 路由实例
 */
const router = useRouter();
//console.log('1-开始创建组件-setup')

const editor = ref<any>();

/**
 * 数据部分
 */
const data = reactive<any>({
  lrcText: "",
  currentLine: 0,
});
const lrcText = ref<any>();
const props = withDefaults(defineProps(), {
  msg: "hello",
  title: () => ["one", "two"],
});
onBeforeMount(() => {
  //console.log('2.组件挂载页面之前执行----onBeforeMount')
});
onMounted(() => {
  // console.log('3.-组件挂载到页面之后执行-------onMounted', currentTime)
});
watchEffect(() => {
  // console.log(data.lrcText);
});
// 使用toRefs解构
// let { } = { ...toRefs(data) }
defineExpose({
  ...toRefs(data),
});

const getline = (selectionStart: number) => {
  let text = data.lrcText.slice(0, selectionStart);
  let line = text.split("\n").length - 1;
  console.log(line, selectionStart);
  data.currentLine = line;
};
const change = (val: string) => {
  console.log(val);
};
const userNameClick = (e: MouseEvent) => {
  let { selectionStart } = e.target as HTMLTextAreaElement;
  getline(selectionStart);
};
const userNameKeyup = (e: KeyboardEvent) => {
  let { selectionStart } = e.target as HTMLTextAreaElement;
  getline(selectionStart);
};

type Type = "add" | "repalce" | "delete";
const operateLrc = async (type: Type) => {
  let textArr: string[] = data.lrcText.split("\n");
  let value = textArr.at(data.currentLine);
  let newText = "";

  if (type === "add") {
    if (value?.lastIndexOf("]") && value?.lastIndexOf("]") > -1) {
      let index = value?.lastIndexOf("]");
      newText =
        value.slice(0, index + 1) +
        currentTimeStr.value +
        value.slice(index + 1);
    } else {
      newText = currentTimeStr.value + value;
    }
  } else if (type === "repalce") {
    let lastIndexL = value?.lastIndexOf("[") ?? -1;
    let lastIndexR = value?.lastIndexOf("]") ?? -1;
    if (value && lastIndexR > lastIndexL) {
      newText =
        value.slice(0, lastIndexL) +
        currentTimeStr.value +
        value.slice(lastIndexR + 1);
    }
  } else if (type === "delete") {
    let lastIndexL = value?.lastIndexOf("[") ?? -1;
    let lastIndexR = value?.lastIndexOf("]") ?? -1;
    if (value && lastIndexR > lastIndexL) {
      newText = value.slice(0, lastIndexL) + value.slice(lastIndexR + 1);
    }
  }

  if (newText) {
    textArr[data.currentLine] = newText;
  }

  data.lrcText = textArr.join("\n");
  editor.value.textarea.focus();
  await nextTick();

  if (data.currentLine + 1 === textArr.length) return;
  // let nextText = textArr.at(data.currentLine + 1)

  let cursorendIndex = textArr.slice(0, data.currentLine + 2).join("\n").length;
  editor.value.textarea.setSelectionRange(cursorendIndex, cursorendIndex);
  data.currentLine++;

  // lrcData.value.lrcText = data.lrcText
};

// watch(() => data.lrcText, (nv, ov) => {
//   lrcData.value.lrcText = nv
// })

const preview = () => {};
const save = () => {
  window.localStorage.setItem(lrcData.value.title, data.lrcText);
  // [al:专辑名]
  // [ar:歌手名]
  // [au:歌词作者-作曲家]
  // [by:此LRC文件的创建者]
  // [offset:+/- 时间补偿值，以毫秒为单位，正值表示加快，负值表示延后]
  // [re:创建此LRC文件的播放器或编辑器]
  // [ti:歌词(歌曲)的标题]
  // [ve:程序的版本]
  let lrcHeader = [];
  if (lrcData.value.album) {
    lrcHeader.push(`[al:${lrcData.value.album}]`);
  }
  if (lrcData.value.artist) {
    lrcHeader.push(`[ar:${lrcData.value.artist}]`);
  }
  if (lrcData.value.editor) {
    lrcHeader.push(`[by:${lrcData.value.editor}]`);
  }
  if (lrcData.value.title) {
    lrcHeader.push(`[ti:${lrcData.value.title}]`);
  }
  let newLrc = lrcHeader.join("\n") + "\n" + data.lrcText;
  const file = new File(
    [newLrc],
    `${lrcData.value.title}-${lrcData.value.artist}.lrc`,
    {
      type: "application/octet-stream",
    }
  );
  const tmpLink = document.createElement("a");
  const objectUrl = URL.createObjectURL(file);

  tmpLink.href = objectUrl;
  tmpLink.download = file.name;
  document.body.appendChild(tmpLink);
  tmpLink.click();
  document.body.removeChild(tmpLink);
  URL.revokeObjectURL(objectUrl);
};
</script>

<template>
  <div class="lrc-editor">
    <el-button-group class="mb-1">
      <el-button
        type="primary"
        :icon="CirclePlus"
        @click.prevent="operateLrc('add')"
        >加入时间标签</el-button
      >
      <el-button
        type="primary"
        :icon="Switch"
        @click.prevent="operateLrc('repalce')"
        >替换时间标签</el-button
      >

      <el-button
        type="primary"
        :icon="Remove"
        @click.prevent="operateLrc('delete')"
        >删减时间标签</el-button
      >
      <el-button type="primary" :icon="View" @click.prevent="preview"
        >预览</el-button
      >
      <el-button type="primary" :icon="Folder" @click.prevent="save"
        >保存</el-button
      >
    </el-button-group>
    <el-input
      ref="editor"
      v-model="lrcData.lrcText"
      @keyup="userNameKeyup($event)"
      @click.prevent="userNameClick"
      :rows="10"
      type="textarea"
      placeholder="请输入歌词"
    />
  </div>
</template>

<style scoped lang="scss">
.lrc-editor {
  margin-top: 0;
}
</style>
